import 'package:flutter_frame/app/components/dialog/app_loading_dialog.dart';
import 'package:flutter_frame/app/components/toast_widget.dart';
import 'package:flutter_frame/app/core/core.dart';
import 'package:flutter_frame/app/core/mixins/http_request_auto_dispose_mixin.dart';
import 'package:flutter_frame/app/core/utils/log_util.dart';
import 'package:flutter_frame/app/core/utils/user_manager.dart';
import 'package:flutter_frame/app/data/api/auth_apis.dart';
import 'package:flutter_frame/app/modules/auth/login/states.dart';
import 'package:flutter_frame/router/app_pages.dart';

class LoginController extends GetxController with HttpRequestAutoDisposeMixin {
  final LoginStates states = LoginStates();

  /// [lastPressedAt] 退出的倒计时
  DateTime? lastPressedAt;

  /// [textEditingControllerUserName] 用户名
  TextEditingController textEditingControllerUserName = TextEditingController();

  /// [textEditingControllerPassword] 密码
  TextEditingController textEditingControllerPassword = TextEditingController();

  // 是否为Android
  bool isAndroid = true;


  @override
  void onInit() {
    super.onInit();
    isAndroid = GetPlatform.isAndroid;
  }

  @override
  void dispose() {
    textEditingControllerUserName.dispose();
    textEditingControllerPassword.dispose();
    super.dispose();
  }


  /// test
  void test() async {

  }

  /// 登录
  void loginDo() async {
    /// executeAutoDispose: 页面关闭，自动销毁请求
    AppLoadingDialog.show();
    final result = await AuthApis.login(
      username: textEditingControllerUserName.value.text,
      password: textEditingControllerPassword.value.text,
    ).executeAutoDispose(this);

    result?..onSuccess((result) {
        print(result.toString());
        AppLoadingDialog.close();
        /// 保存token
        if(result.data != null) {
          UserManager.saveToken(result.data?.accessToken);
          UserManager.saveUser(result.data!);
          Get.offAllNamed(AppRoutes.home);
        }

      })
      ..onError((result) {
        AppToast.showError(result.msg);
        AppLoadingDialog.close();
      })
      ..onCancel((result) {
        AppLoadingDialog.close();
      });

  }

  /// 重置账号
  void reset() async {
    textEditingControllerUserName.clear();
    textEditingControllerPassword.clear();
  }




  /// 登录完跳转
  void goHome() {
    AppLoadingDialog.show();
    Future.delayed(const Duration(milliseconds: 200)).then((value) {
      // 直到首页
      AppLoadingDialog.close();
      Get.offAndToNamed(AppRoutes.home);
    });
  }
}
